// 轮播管理
import React, { useEffect, useState } from 'react';
import { Input, Select, Space, Collapse, Button, Form, Table, DatePicker, Switch, Image, Modal, message, ConfigProvider } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { TableRowSelection } from 'antd/es/table/interface';
import AddorRev from './oSlideChild/AddorRev';
import zh_CN from 'antd/es/locale/zh_CN';
import '../../css/operation.css'
import getSelectTime from '../../../utils/date'
import { getSlide, delSlide, delBatchSlide } from '../../../api/opreationApi'// 表格
interface DataType {
  key: React.Key;
  carouselTital: string;//名字
  carouselId: number;//序号
  carouselTimePar: string;//上架时间段
  carouselLocation: number;//位置
  carouselType: string;//类型
  carouselPic: string;//图片
  carouselTime: string;//上架时间
  carouselUpordown: number;//是否上架
  carouselUptimeStart: string;
  carouselIuptimeEnd: string;
}

export default function OperationSlide() {
  const [slideData, setSlideData] = useState<DataType[]>([])//当前页渲染数据
  const [pageSize, setPageSize] = useState<number>(5) //每页条数
  const [currentPage, setCurrentPage] = useState<number>(1) //当前第几页
  const [total, setTotal] = useState<number>()//总条数
  const [state, setState] = useState<number>()//状态
  const [keyWord, setKeyWord] = useState<string>()//关键字
  const [upTime, setUpTime] = useState<string>()//上架时间
  const [sortWay, setSortWay] = useState<string>()//选择排序方式
  const [selectedRow, setSelectedRow] = useState<DataType[]>([]);//多选选中的数据
  // 拿初始数据函数 查询 排序
  const getData = () => {
    getSlide({
      currentPage, pageSize, state, keyWord, sortWay, upTime
    }).then(res => {
      setSlideData(res.data.list)
      setTotal(res.data.total)
    })
  }

  // 请求数据渲染页面
  useEffect(() => {
    getData()
  }, [pageSize, currentPage, sortWay, upTime, keyWord, state])

  //页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
  const pageChange = (page: number, pageSize: number) => {
    setPageSize(pageSize)
    setCurrentPage(page)
  }


  const { Panel } = Collapse;//折叠面板
  // 表格
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[], row: DataType[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setSelectedRow(row)
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'carouselId',
    },
    {
      title: '轮播标题',
      dataIndex: 'carouselTital',
    },
    {
      title: '封面图',
      dataIndex: 'carouselPic',
      render: (_, record) => (
        <Image
          width={50}
          height={50}
          src={`http://dsq.ljc.icu:8080` + record.carouselPic}
        />
      ),
    },
    {
      title: '位置',
      dataIndex: 'carouselLocation',
    },
    {
      title: '是否上架',
      dataIndex: 'carouselUpordown',
      render: (_, record) => (
        <Switch checked={record.carouselUpordown === 1 ? true : false} />
      ),
    },
    {
      title: '上架时间段',
      render: (_, record) =>
        `${record.carouselUptimeStart}~${record.carouselIuptimeEnd}`
    },
    {
      title: '上架时间',
      dataIndex: 'carouselTime',
    },
    {
      title: '类型',
      dataIndex: 'carouselType',
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" className='edmit' onClick={() => rev(record)}>编辑</Button>
          <Button id='del' onClick={() => showConfirm(record)}>删除</Button>
        </Space >
      ),
    },
  ];

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  // 操作部分
  const [form] = Form.useForm();//使用From表单，用于默认值
  // （1）删除
  // 删除弹框
  const { confirm } = Modal;
  const showConfirm = (record?: any) => {
    confirm({
      title: '提示:',
      icon: <ExclamationCircleFilled />,
      content: '您确定要删除吗？删除后无法恢复！',
      cancelText: '取消',
      okText: '确认',
      onOk() {
        if (Array.isArray(record)) {
          delBatchSlide(record).then(res => { getData() })
          message.success('批量删除成功！')
        } else {
          delSlide({ carouselId: record.carouselId }).then(res => { getData() })
          message.success('删除成功！')
        }
      },
    });
  };

  // （2）添加和编辑共用弹框
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);//是否显示对话框
  const [head, setHead] = useState<string | null>(null);
  const [nowRev, setNowRev] = useState<DataType | null>(null)

  // 添加
  const add = (): void => {
    setIsModalOpen(true)
    setHead('添加')
  }
  // 编辑
  const rev = (record: any): void => {
    setIsModalOpen(true)
    setNowRev(record)
    setHead('编辑')
  }

  // (3)查询
  //日期选择
  const { RangePicker } = DatePicker;
  // 查询按钮
  const sreach = (values: any) => {
    setUpTime(values.upTime ? getSelectTime(values.upTime) : upTime)
    setKeyWord(values.keyWord)
    setState(values.state === '未上架' ? 0 : values.state === '已上架' ? 1 : state)
  }

  // (4)重置
  const reset = () => {
    form.resetFields()
    message.success('重置成功！')
    getSlide({
      currentPage, pageSize
    }).then(res => {
      setSlideData(res.data.list)
      setTotal(res.data.total)
    })
  }

  // 批量删除
  const batchDel = () => {
    // 判断用户是否已选择
    if (selectedRowKeys.length > 0) {
      let carouselId = selectedRow.map(item => item.carouselId)
      showConfirm(carouselId)
    } else {
      // 提示用户选择
      message.error('请选择删除项！')
    }
  }

  // 自定义添加编辑弹框消失
  const modalClose = () => {
    setIsModalOpen(false);
  }

  // 排序下拉框
  const handleChangeSort = (value: string) => {
    setSortWay(value)
    getData()
  }

  return (<div>
    {/* 头部标题 */}
    <p className='head'>轮播管理</p>
    {/* 搜索操作 */}
    <Collapse className='collapse' defaultActiveKey={['1']}>
      <Panel header="筛选查询" key="1">
        <div className='operate-wrap operate-left'>
          <Form form={form} className='operate-left operate-left-item' onFinish={sreach}>
            <Form.Item label="关键词：" className='operate-left-item' name='keyWord' >
              <Input placeholder="标题关键词" className='search' />
            </Form.Item>
            <Form.Item label='状态：' className='operate-left-item' name='state'>
              <Select
                style={{ width: 120 }}
                allowClear
                options={[{ value: '未上架', label: '未上架' }, { value: '已上架', label: '已上架' }]}
                className='drop'
                placeholder="请选择状态"
              />
            </Form.Item>
            <Form.Item label='上架时间：' className='operate-left-item' name='upTime'>
              <DatePicker showTime placeholder="请选择上架时间" />
            </Form.Item>
            <Form.Item>
              <Button className='inquire operate-left-item' htmlType='submit'>查询</Button>
              <Button className='reset operate-left-item' onClick={reset}>重置</Button>
            </Form.Item>
          </Form>
        </div>
      </Panel>
    </Collapse>
    {/* 表格列表整体 */}
    <div className='table'>
      {/* 表格操作 */}
      <div className='operationTable'>
        {/* 排序 */}
        <Form>
          <Form.Item label='排序：' className='operate-left-item' name='sortWay'>
            <Space wrap>
              <Select
                onChange={handleChangeSort}
                style={{ width: 120 }}
                allowClear
                options={[{ value: '按时间顺序', label: '按时间顺序' }, { value: '按时间倒序', label: '按时间倒序' }]}
                className='drop'
                placeholder="请选择方式"
              />
            </Space>
          </Form.Item>
        </Form>
        <Button id='del' className='operate-left-item' onClick={batchDel}>批量删除</Button>
        <Button className='add' onClick={add}>添加</Button>
      </div>
      {/* 表格 */}
      <ConfigProvider locale={zh_CN}>
        <Table rowSelection={rowSelection}
          columns={columns}
          rowKey={item => item.carouselId}
          dataSource={slideData}
          pagination={{
            position: ['bottomRight'],
            defaultPageSize: 5,
            pageSizeOptions: [2, 3, 5, 6],
            showQuickJumper: true,
            showSizeChanger: true,
            total: total,
            onChange: pageChange,
            pageSize: pageSize,
            showTotal: (total: number) => (`共有 ${total} 条数据`)
          }} />
      </ConfigProvider>
    </div>
    {/* 增加编辑共用弹框 */}
    <AddorRev getData={getData} modalClose={modalClose} isModalOpen={isModalOpen} head={head} nowRev={nowRev}></AddorRev>
  </div >)
}
